<?php
    @include_once("conn.php");

    
    if(!( isset($_GET["key"]) && isset($_GET["orderCol"]) && isset($_GET["orderType"]) && isset($_GET["pageIndex"]) && isset($_GET["showNum"]))){
        $obj = array();
        $obj["status"] = false;
        $obj["msg"] = "请传入完整参数";
        $json = json_encode($obj);
        exit($json);
    }

    $key = $_GET["key"];
    $orderCol = $_GET["orderCol"];    // 排序的列名(字段名)
    $orderType = $_GET["orderType"];  // 排序的方式( asc desc)
    $pageIndex = $_GET["pageIndex"];  // 查询的页码  第几页
    $showNum = $_GET["showNum"];      // 每页显示多少条

    $searchAll = "select count(*) as count from  `goodslist` where goodsName like '%$key%'";

    $resultAll = mysqli_query($conn,$searchAll);

    if(!$resultAll){
        $obj =array();
        $obj["status"] = false;
        $obj["msg"] = "请传入完整参数";
        $obj["sql"] = $searchAll;
        $json = json_encode($obj);
        exit($json);
    }

    $obj = array();
    if($resultAll){
        $item = mysqli_fetch_assoc($resultAll);

        $count = $item["count"];

        if($count==0){
            $obj = array();
            $obj["status"] = false;
            $obj["msg"] = "请传入完整参数";
            $json = json_encode($obj);
            exit($json);
        }

        $maxPage = ceil($count / $showNum);

        // 临界值限制
        if($pageIndex > $maxPage) $pageIndex = $maxPage;
        if($pageIndex < 1) $pageIndex = 1;
       
        $skipNum = ( $pageIndex - 1) * $showNum;

        $sql = "select id,goodsId,goodsName,goodsImg,goodsPrice from  `goodslist_copy` where goodsName like '%$key%' order by $orderCol $orderType limit $skipNum,$showNum";
        // 执行mysql语句
        $result = mysqli_query($conn,$sql);

        if($result){
            $list = array();
            // 解析数据  => 赋值给变量 $item  =>  有数据,循环解析  没有数据(null) =>跳出循环
            while($item = mysqli_fetch_assoc($result)){
                array_push($list,$item);
            }

            $obj["status"] = true;
            $obj["msg"] = "OK";
            //  前端需要
            $obj["currentIndex"] = $pageIndex*1;
            $obj["count"] = $count*1;
            $obj["maxPage"] = $maxPage*1;

            $obj["list"] = $list;
        }else{
            $obj["status"] = false;
            $obj["msg"] = "sql语句有误";
            $obj["sql"] = $sql;
        }
    }else{
        $obj["status"] = false;
        $obj["msg"] = "sql语句有误";
        $obj["sql"] = $sql;
    }

    echo json_encode($obj);

?>
